<?php

namespace App\Http\Middleware;

use App\Models\Roles;
use Closure;
use Illuminate\Http\Exceptions\HttpResponseException;

class AuthenAccess
{

    public function handle($request, Closure $next)
    {
        $current = $request->route()->getName();
        $result = $this->getAccessRoute($current);
        if($result){
            return $next($request);
        }else {
            if ($request->ajax()) {
                $data = [
                    "code" => 1,
                    "data" => null,
                    "msg" => '抱歉，您没有操作权限'
                ];
                throw (new HttpResponseException(response()->json($data)));
            }
            return response()->view("admin.errors.403", [], 403);
        }
    }

    /**
     * 返回权限节点
     * @param $current 当前路由
     * @return array
     */
    protected function getAccessRoute($current)
    {
        $menus = config('menu.manage');
        $code = '';
        foreach($menus as $key=>$menu){
            foreach($menu['node'] as $ke=>$node){
                foreach($node['child'] as $k=>$child){
                    if($current == $child['url']){
                        $code = $k;
                        break;
                    }
                }
            }
        }
        if($code && auth()->user()->role_id>1){
            $roles = Roles::adminRole();
            return in_array($code,$roles);
        }
        return true;
    }
}
